<template>
  <div class="app-container">
  
    
    <!-- 按钮区域 -->
    <div class="mb20">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button type="info" plain icon="el-icon-menu" @click="showParentCategories">查询所有父类</el-button>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="uniqueId"
        :default-expand-all="true"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        border>
        <el-table-column
          prop="name"
          label="分类名称"
          min-width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.children && scope.row.children.length > 0" class="folder-icon">
              <i class="el-icon-folder"></i>
            </span>
            <span v-else class="file-icon">
              <i class="el-icon-document"></i>
            </span>
            {{ scope.row.name || '未命名' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="code"
          label="分类编码"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180">
        </el-table-column>
        <el-table-column
          prop="createBy"
          label="创建人"
          min-width="120">
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="200"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleAddChild(scope.row)"
              style="color: #0d84ff;">
              新建子分类
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
              style="color: #0d84ff;">
              编辑
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
              style="color: #ff4d4f;">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分类添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="categoryForm" label-width="80px">
        <!-- 父分类表单项 -->
        <template v-if="isParent">
          <el-form-item label="分类名称" prop="material_classification_name">
            <el-input v-model="form.material_classification_name" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item label="分类编码" prop="material_classification_code">
            <el-input v-model="form.material_classification_code" placeholder="请输入分类编码"></el-input>
          </el-form-item>
        </template>
        
        <!-- 子分类表单项 -->
        <template v-else>
          <el-form-item label="分类名称" prop="material_subcategory_name">
            <el-input v-model="form.material_subcategory_name" placeholder="请输入子分类名称"></el-input>
          </el-form-item>
          <el-form-item label="分类编码" prop="material_subcategory_code">
            <el-input v-model="form.material_subcategory_code" placeholder="请输入子分类编码"></el-input>
          </el-form-item>
        </template>
        
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 导入对话框 -->
    <import-dialog ref="importDialog" @ok="getList" />
  </div>
</template>

<script>
import { listMaterialCategory, addMaterialCategory, updateMaterialCategory, delMaterialCategory, listAllParentCategories } from '@/api/basic/materialCategory'
import ImportDialog from './importDialog'
import request from '@/utils/request'

export default {
  name: 'BasicWlfl',
  components: {
    ImportDialog
  },
  data() {
    return {
      // 表格数据
      loading: false,
      tableData: [],
      
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '添加分类',
      isEdit: false,
      isParent: true,
      form: {
        material_classification_id: null,
        material_classification_name: '',
        material_classification_code: '',
        remark: ''
      },
      rules: {
        material_classification_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        material_classification_code: [
          { required: true, message: '请输入分类编码', trigger: 'blur' }
        ],
        material_subcategory_name: [
          { required: true, message: '请输入子分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        material_subcategory_code: [
          { required: true, message: '请输入子分类编码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取分类列表
    getList() {
      this.loading = true
      
      // 直接使用分步获取方法
      this.getParentAndChildrenSeparately()
    },
    
    // 分步获取父分类和子分类
    getParentAndChildrenSeparately() {
      // 先获取父分类
      listAllParentCategories().then(response => {
        if (response.code === 200) {
          const parentData = response.data || response.rows || []
          
          console.log('原始父分类数据:', parentData)
          
          // 处理父分类数据
          const processedParentData = parentData.map(item => {
            return {
              id: item.material_classification_id,
              name: item.material_classification_name,
              code: item.material_classification_code,
              createTime: item.create_time,
              createBy: item.create_by,
              updateTime: item.update_time,
              updateBy: item.update_by,
              remark: item.remark || '',
              isParent: true,
              children: [],
              uniqueId: 'p_' + item.material_classification_id // 添加带前缀的uniqueId
            }
          })
          
          // 再获取子分类
          this.getSubcategories(processedParentData)
        } else {
          this.$message.error(response.msg || '获取父分类失败')
          this.loading = false
        }
      }).catch(error => {
        console.error('获取父分类失败', error)
        this.$message.error('获取父分类失败，请稍后重试')
        this.loading = false
      })
    },
    
    // 获取子分类
    getSubcategories(parentData) {
      // 构建查询参数
      const queryParams = {}
      
      // 查询子分类
      listMaterialCategory(queryParams).then(response => {
        if (response.code === 200) {
          const rawData = response.data || response.rows || []
          console.log('子分类API原始返回数据:', rawData)
          
          // 创建一个映射，用于快速查找父分类ID对应的索引
          const parentIdMap = {};
          parentData.forEach((parent, index) => {
            parentIdMap[parent.id] = index;
          });
          
          // 初始化所有父分类的children数组
          parentData.forEach(parent => {
            parent.children = [];
          });
          
          // 处理子分类数据
          rawData.forEach(item => {
            // 获取父分类ID
            const parentId = item.material_classification_id;
            
            // 如果找到对应的父分类
            if (parentId && parentIdMap[parentId] !== undefined) {
              const parentIndex = parentIdMap[parentId];
              
              // 添加子分类到对应的父分类下
              parentData[parentIndex].children.push({
                id: item.material_subcategory_id,
                name: item.material_subcategory_name,
                code: item.material_subcategory_code,
                createTime: item.create_time,
                createBy: item.create_by,
                updateTime: item.update_time,
                updateBy: item.update_by,
                remark: item.remark || '',
                parentId: parentId,
                isParent: false,
                uniqueId: 'c_' + item.material_subcategory_id
              });
            }
          });
          
          console.log('处理后的数据:', parentData);
          
          // 更新表格数据
          this.tableData = parentData;
          this.loading = false;
        } else {
          this.$message.error(response.msg || '获取子分类失败')
          this.loading = false
        }
      }).catch(error => {
        console.error('获取子分类失败', error)
        this.$message.error('获取子分类失败，请稍后重试')
        this.loading = false
      })
    },
    
    // 添加分类
    handleAdd() {
      this.dialogTitle = '添加分类'
      this.isEdit = false
      this.isParent = true
      this.form = {
        material_classification_id: null,
        material_classification_name: '',
        material_classification_code: '',
        remark: ''
      }
      this.dialogVisible = true
    },
    
    // 添加子分类
    handleAddChild(row) {
      this.dialogTitle = '添加子分类'
      this.isEdit = false
      this.isParent = false
      this.form = {
        material_subcategory_id: null,
        material_subcategory_name: '',
        material_subcategory_code: '',
        material_classification_id: row.id,
        remark: ''
      }
      this.dialogVisible = true
    },
    
    // 编辑分类
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.isEdit = true
      this.isParent = row.isParent
      
      if (row.isParent) {
        // 编辑父分类
        this.form = {
          material_classification_id: row.id,
          material_classification_name: row.name,
          material_classification_code: row.code,
          remark: row.remark || ''
        }
      } else {
        // 编辑子分类
        this.form = {
          material_subcategory_id: row.id,
          material_subcategory_name: row.name,
          material_subcategory_code: row.code,
          material_classification_id: row.parentId,
          remark: row.remark || ''
        }
      }
      
      this.dialogVisible = true
    },
    
    // 删除分类
    handleDelete(row) {
      const apiUrl = row.isParent ? 
        '/ldzl-basic/wlfl/dp/' + row.id : 
        '/ldzl-basic/wlflz/dp/' + row.id
      
      this.$confirm('确认删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据是父分类还是子分类调用不同的删除API
        if (row.isParent) {
          // 删除父分类
          request({
            url: apiUrl,
            method: 'put',
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(response => {
            this.$message.success('删除成功!')
            this.getList()
          }).catch(error => {
            console.error('删除失败', error)
            let errorMsg = '删除失败: ';
            if (error.response) {
              errorMsg += error.response.status + ' ' + (error.response.data?.msg || error.message);
            } else {
              errorMsg += error.message || '请稍后重试';
            }
            this.$message.error(errorMsg)
          })
        } else {
          // 删除子分类
          delMaterialCategory(row.id).then(() => {
            this.$message.success('删除成功!')
            this.getList()
          }).catch(error => {
            console.error('删除失败', error)
            let errorMsg = '删除失败: ';
            if (error.response) {
              errorMsg += error.response.status + ' ' + (error.response.data?.msg || error.message);
            } else {
              errorMsg += error.message || '请稍后重试';
            }
            this.$message.error(errorMsg)
          })
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.categoryForm.validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.form)
          
          // 根据是否为父分类构建不同的请求数据
          if (this.isParent) {
            // 父分类数据结构 - 直接使用表单数据
            const requestData = {
              material_classification_name: data.material_classification_name,
              material_classification_code: data.material_classification_code,
              remark: data.remark
            }
            
            // 只在编辑时提供ID
            if (this.isEdit && data.material_classification_id) {
              requestData.material_classification_id = data.material_classification_id
            }
            
            console.log('发送父分类数据:', requestData)
            
            // 调用父分类API
            const apiUrl = '/ldzl-basic/wlfl/'
            const method = this.isEdit ? 'put' : 'post'
            
            request({
              url: apiUrl,
              method: method,
              data: requestData
            }).then(response => {
              if (response.code === 200) {
                this.$message.success(this.isEdit ? '编辑成功!' : '添加成功!')
                this.dialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.msg || (this.isEdit ? '编辑失败' : '添加失败'))
              }
            }).catch(error => {
              console.error(this.isEdit ? '编辑失败' : '添加失败', error)
              this.$message.error(this.isEdit ? '编辑失败，请稍后重试' : '添加失败，请稍后重试')
            })
          } else {
            // 子分类数据结构
            const requestData = {
              material_subcategory_name: data.material_subcategory_name,
              material_subcategory_code: data.material_subcategory_code,
              material_classification_id: data.material_classification_id,  // 使用父ID，字段名改为material_classification_id
              parent_id: data.material_classification_id,  // 添加备用字段
              remark: data.remark
            }
            
            // 打印请求数据，确认父ID是否正确设置
            console.log('子分类请求数据:', JSON.stringify(requestData))
            
            // 只在编辑时提供ID
            if (this.isEdit && data.material_subcategory_id) {
              requestData.material_subcategory_id = data.material_subcategory_id
            }
            
            console.log('发送子分类数据:', requestData)
            
            if (this.isEdit) {
              updateMaterialCategory(requestData).then(response => {
                if (response.code === 200) {
                  this.$message.success('编辑成功!')
                  this.dialogVisible = false
                  this.getList()
                } else {
                  this.$message.error(response.msg || '编辑失败')
                }
              }).catch(error => {
                console.error('编辑子分类失败', error)
                this.$message.error('编辑失败，请稍后重试')
              })
            } else {
              addMaterialCategory(requestData).then(response => {
                if (response.code === 200) {
                  this.$message.success('添加成功!')
                  this.dialogVisible = false
                  this.getList()
                } else {
                  this.$message.error(response.msg || '添加失败')
                }
              }).catch(error => {
                console.error('添加子分类失败', error)
                this.$message.error('添加失败，请稍后重试')
              })
            }
          }
        } else {
          return false
        }
      })
    },
    
   
    
    // 显示所有父分类
    showParentCategories() {
      // 获取所有父分类
      listAllParentCategories().then(response => {
        if (response.code === 200) {
          const parentData = response.data || response.rows || []
          
          if (parentData.length === 0) {
            this.$message.info('暂无父类分类数据')
            return
          }
          
          // 构建一个展示用的数组
          const displayData = parentData.map(item => {
            return {
              id: item.material_classification_id,
              name: item.material_classification_name,
              code: item.material_classification_code,
              createTime: item.create_time,
              createBy: item.create_by
            }
          })
          
          // 使用Element UI的MessageBox显示父类列表
          this.$alert(
            '<div style="max-height: 300px; overflow-y: auto;">' +
            '<table class="el-table" style="width: 100%;">' +
            '<thead><tr><th>ID</th><th>名称</th><th>编码</th></tr></thead>' +
            '<tbody>' +
            displayData.map(item => 
              `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.code}</td></tr>`
            ).join('') +
            '</tbody></table></div>',
            '父类分类列表',
            {
              dangerouslyUseHTMLString: true,
              closeOnClickModal: true,
              closeOnPressEscape: true,
              showConfirmButton: false
            }
          )
        } else {
          this.$message.error(response.msg || '获取父分类失败')
        }
      }).catch(error => {
        console.error('获取父分类失败', error)
        this.$message.error('获取父分类失败，请稍后重试')
      })
    }
  }
}
</script>

<style scoped>
.app-breadcrumb {
  margin-bottom: 20px;
}
.mb20 {
  margin-bottom: 20px;
}
.folder-icon, .file-icon {
  margin-right: 5px;
}
.folder-icon i {
  color: #e6a23c;
}
.file-icon i {
  color: #909399;
}
.app-container {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto; /* Added for scrolling */
}
.table-container {
  height: calc(100vh - 280px); /* Adjusted height for table */
  overflow-y: auto; /* Added for scrolling */
}
</style>
